package com.lty.controller;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lty.common.BaseResponse;
import com.lty.common.ErrorCode;
import com.lty.common.PageRequest;
import com.lty.common.ResultUtils;
import com.lty.constant.QuartzJobConstant;
import com.lty.exception.BusinessException;
import com.lty.model.entity.QuartzJob;
import com.lty.service.QuartzJobService;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/job")
public class QuartzJobController {

    private final QuartzJobService jobService;

    public QuartzJobController(QuartzJobService jobService) {
        this.jobService = jobService;
    }

    /**
     * 获取所有任务列表
     */
    @PostMapping("/list")
    public List<QuartzJob> listJobs() {
        return jobService.list();
    }

    @PostMapping("/list/page")
    public BaseResponse<Page<QuartzJob>> listJobsByPage(@RequestBody PageRequest request) {
        // 分页基本字段
        long current = request.getCurrent();
        long size = request.getPageSize();
        // 反爬虫
        if (size > 100) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "查询数量过多");
        }
        Page<QuartzJob> page = new Page<>(current, size);
        QueryWrapper<QuartzJob> qw = new QueryWrapper<>();
        Page<QuartzJob> quartzJobPage = jobService.page(page,qw);
        return ResultUtils.success(quartzJobPage);
    }

    /**
     * 添加任务
     */
    @PostMapping("/add")
    public BaseResponse<String> addJob(@RequestBody QuartzJob job) {
        try {
            job.setId(IdUtil.simpleUUID());
            jobService.addJob(job);
            // 保存到数据库
            jobService.save(job);
            return ResultUtils.success("任务添加成功");
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "任务添加失败: " + e.getMessage());
        }
    }

    /**
     * 更新任务
     */
    @PostMapping("/update")
    public BaseResponse<String> updateJob(@RequestBody QuartzJob job) {
        try {
            jobService.updateJob(job);
            return ResultUtils.success("任务更新成功");
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "任务更新失败: " + e.getMessage());
        }
    }

    /**
     * 删除任务
     */
    @PostMapping("/{jobId}/delete")
    public BaseResponse<String> deleteJob(@PathVariable String jobId) {
        try {
            jobService.deleteJob(jobId);
            return ResultUtils.success("任务删除成功");
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "任务删除失败: " + e.getMessage());
        }
    }

    /**
     * 暂停任务
     */
    @PostMapping("/{jobId}/pause")
    public BaseResponse<String> pauseJob(@PathVariable String jobId) {
        try {
            jobService.pauseJob(jobId);
            return ResultUtils.success("任务暂停成功");
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "任务暂停失败: " + e.getMessage());
        }
    }

    /**
     * 恢复任务
     */
    @PostMapping("/{jobId}/resume")
    public BaseResponse<String> resumeJob(@PathVariable String jobId) {
        try {
            jobService.resumeJob(jobId);
            return ResultUtils.success("任务恢复成功");
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "任务恢复失败: " + e.getMessage());
        }
    }

    /**
     * 立即执行任务
     */
    @PostMapping("/{jobId}/runNow")
    public BaseResponse<String> runJobNow(@PathVariable String jobId) {
        try {
            jobService.runJobNow(jobId);
            return ResultUtils.success("任务立即执行成功");
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "任务立即执行失败: " + e.getMessage());
        }
    }


    /**
     * 重启定时任务
     */
    @PostMapping("/restart")
    public BaseResponse<Boolean> restart() {
        Boolean result = true;
        try {
            List<QuartzJob> list = jobService.list();
            for (QuartzJob job : list) {
                if (job.getStatus() == QuartzJobConstant.JOB_STATUS_NORMAL) {
                    // 0-正常，重新添加任务
                    jobService.addJob(job);
                } else if (job.getStatus() == QuartzJobConstant.JOB_STATUS_PAUSED) {
                    // 1-暂停，暂停任务
                    jobService.pauseJob(job.getId());
                }
            }
            return ResultUtils.success(result);
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "重启定时任务失败: " + e.getMessage());
        }
    }
}